# @Time    : 2020-03-12-0012 21:11
# @Author  : V万能的小黑V
# @File    : bd_image.py

# 从Python SDK导入BOS配置管理模块以及安全认证模块
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
# 导入BOS相关模块
from baidubce.services.bos.bos_client import BosClient


class Bd_Storage(object):
    def __init__(self):
        # 设置BosClient的Host，Access Key ID和Secret Access Key
        self.bos_host = "gz.bcebos.com/"  # 地址可以改，参考百度的python SDK文档
        self.access_key_id = "c222b7a093604976be5ca0b27f977785"
        self.secret_access_key = "fe95ef95a3294973adbe81bc3f9bca4b"
        self.bucket_name = "img888"

    def up_image(self, key_name, file):
        config = BceClientConfiguration(credentials=BceCredentials(self.access_key_id, self.secret_access_key),
                                        endpoint=self.bos_host)
        client = BosClient(config)
        exists = client.does_bucket_exist(self.bucket_name)
        print(exists)
        key_name = key_name
        try:
            res = client.put_object_from_string(bucket=self.bucket_name, key=key_name, data=file)
        except Exception as e:
            return None
        else:
            result = res.__dict__
            if result['metadata']:
                # print("图片上传成功:{}".format("https://" + self.back_name + ".bj.bcebos.com/" + key_name))
                url = 'https://cdnimg.junjs.cn/' + key_name
                print("图片上传成功:{}".format(url))


# 测试
with open('E:/Company/WorkPlace/system/images/2020428/5bbb30351a2c4646be729ec66f572079.png', 'rb') as f:
    bd = Bd_Storage()

    s = f.read()
    bd.up_image("5bbb30351a2c4646be729ec66f572079.png", s)
